package com.niepan.modules.zhinenganjianback.common;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UdpServer {

    private final static Logger logger = LoggerFactory.getLogger(UdpServer.class);
    private static int PORT = 9000;
    private static final String HOST = "192.168.2.100";

    private static volatile UdpServer instance = null;

    public static ChannelHandlerContext chx =null;
    public static DatagramPacket datagramPacket = null;


    //左摆
    public static final byte[] leftBytes = new byte[]{(byte) 0xAA, (byte) 0xAA,0x01,0x00,0x00,0x00,(byte) 0x0F, 0x00,0x3A,0x01,0x1A,0x00,0x20,0x00,0x01};

    //右摆
    public static final byte[] rightBytes = new byte[]{(byte) 0xAA, (byte) 0xAA,0x01,0x00,0x00,0x00,(byte) 0x0F, 0x00,0x3A,0x01,0x1A,0x01,0x20,0x00,0x00};

    //回正
    public static final byte[] backBytes = new byte[]{(byte) 0xAA, (byte) 0xAA,0x01,0x00,0x00,0x00,(byte) 0x0F, 0x00,0x3A,0x01,0x1A,0x01,0x10,0x00,0x02};

    public static UdpServer getInstance() {
        if (instance == null) {
            synchronized (UdpServer.class) {
                if (instance == null) {
                    instance = new UdpServer();
                }
            }
        }
        return instance;
    }

    public UdpServer() {
        init();
    }

    /**
     * 初始化
     */
    private static void init() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    // DatagramChannel是一个能收发UDP包的通道。因为UDP是无连接的网络协议，所以不能像其它通道那样读取和写入。它发送和接收的是数据包。
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpServerHandler());
            b.bind(HOST,PORT).sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理客户端请求
     */
    private static class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
            //TODO 打印设备上报的报文
            getMsg(packet);
            chx = ctx;
            datagramPacket = packet;
        }
    }

    /**
     * 获取客户端消息，并打印到控制台
     *
     * @param packet
     */
    private static void getMsg(DatagramPacket packet) {
        ByteBuf buf = packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        processPackageData(req);
    }

    private static void processPackageData(byte[] bs){
        //TODO  设备上报的报文指令
        logger.info("服务器收到指令:【{}】", ByteBufUtil.hexDump(bs));
    }

    /**
     * 自动回复消息
     *
     * @param bytes
     */
    public static void returnMsg(byte[] bytes) {
        DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), datagramPacket.sender());
        chx.channel().writeAndFlush(data);//向客户端发送消息
    }
}
